package com.xiaoxi.bms.common.filter;

import com.xiaoxi.bms.common.constant.enumeration.statuscode.system.TokenSystemEnums;
import com.xiaoxi.bms.common.exception.BMSSecurityException;
import com.xiaoxi.bms.common.response.ApiResponse;
import com.xiaoxi.bms.common.util.AuthUtils;
import com.xiaoxi.bms.common.util.JwtTokenUtils;
import com.xiaoxi.bms.domain.user.BMSUser;
import com.xiaoxi.bms.domain.user.BMSUserContext;
import com.xiaoxi.bms.service.user.BMSUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
/**
 * @Author xiaoxi
 * @ProjectName bms
 * @PackageName com.xiaoxi.bms.common.filter
 * @ClassName JwtAuthorizationTokenFilter
 * @Description TODO
 * @Date 2023/6/5 12:22
 * @Version 1.0
 */
@Component
@Slf4j
public class JwtAuthorizationTokenFilter extends OncePerRequestFilter {

    @Value("${jwt.token-header}")
    private String tokenHeader;

    @Value("${jwt.token-head}")
    private String tokenHead;

    @Resource
    private BMSUserService bmsUserService;

    @Resource
    private AuthenticationFailureHandler authenticationFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException, NumberFormatException {

        try {
            if (!StringUtils.equals("/bms/user/api/v1/login", request.getRequestURI())
                    && !StringUtils.equals("/bms/code/api/v1/getVerificationCode", request.getRequestURI())
                    && !StringUtils.equals("/bms/user/api/v1/changeUserPassword", request.getRequestURI())) {
                authenticationToken(request);
            }
        } catch (BMSSecurityException e) {
            authenticationFailureHandler.onAuthenticationFailure(request, response, e);
            return;
        }

        // 放行
        chain.doFilter(request, response);
    }


    /**
     * 认证 token
     *
     * @param request 请求
     * @throws BMSSecurityException
     */
    private void authenticationToken(HttpServletRequest request) throws BMSSecurityException {
        // 获取Header
        String authHeader = request.getHeader(tokenHeader);

        // 请求头 未带上 - Authorization
        if (StringUtils.isEmpty(authHeader)) {
            throw new BMSSecurityException(TokenSystemEnums.HEADER_AUTHORIZATION_NOT_CARRY);
        }

        // 虽然 请求头 带上了 - Authorization，但是 前缀 不符合 规定
        if (!authHeader.startsWith(tokenHead)) {
            throw new BMSSecurityException(TokenSystemEnums.HEADER_AUTHORIZATION_FAIL);
        }

        // 字段截取authToken
        String authToken = authHeader.substring(tokenHead.length());

        // 根据authToken获取username
        // 2.1.2.2 校验 token是否失效
        BMSUserContext bmsUserContext = JwtTokenUtils.getUserToken(authToken);
        log.info("用户信息 : {}", bmsUserContext);
        if (Objects.isNull(bmsUserContext)) {
            log.error("token失效");
            throw new BMSSecurityException(TokenSystemEnums.TOKEN_INVALID);
        }

        // token 有效，但是 上下文已经没了
        if (Objects.isNull(AuthUtils.getAuthentication())) {
            // 登录
            String username = bmsUserContext.getUsername();
            BMSUser bmsUser = (BMSUser) bmsUserService.loadUserByUsername(username);

            // 验证token是否已经过期了
            if (!JwtTokenUtils.isTokenExpired(authToken)) {

                UsernamePasswordAuthenticationToken authenticationToken =
                        new UsernamePasswordAuthenticationToken(bmsUser, "", bmsUser.getAuthorities());

                // 重新设置到用户对象里
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);

            } else {
                // token 过期
                throw new BMSSecurityException(TokenSystemEnums.TOKEN_OVERDUE);
            }
        }

    }

}
